import {Request, Response} from "express";
import {checkParams, clone} from "@src/util/util";
import Constant from "@src/util/constant";
import dictServer from "@src/services/dictServer";

const paths = {
  add: "/dict",
  delete: "/dict/:id",
  list: "/dict-list",
  update: "/dict/:id",
  category: "/dict-category/:id",
};

// 添加数据字典
const add = async (req: Request, res: Response) => {
  const flag = checkParams(req.body, ["type_id", "name"]);
  if (!flag) {
    return res.json({data: Constant.LACK});
  } else {
    const typeId = req.body.type_id;
    const name = req.body.name;
    const data = await dictServer.add(typeId, name);
    return res.json({data});
  }
};

// 更新数据字典
const update = async (req: Request, res: Response) => {
  const flag = checkParams(req.body, ["type_id", "name"]);
  const id = req.params.id as string;
  if (!flag || !id) {
    return res.json({data: Constant.LACK});
  } else {
    const typeId = req.body.type_id;
    const name = req.body.name;
    const data = await dictServer.update(id, typeId, name);
    return res.json({data});
  }
};

// 删除
const _delete = async (req: Request, res: Response) => {
  const id = req.params.id;
  if (id === "undefined") {
    return clone(Constant.LACK);
  }
  const data = await dictServer._delete(id);
  return res.json({data});
};

// 字典列表
const list = async (req: Request, res: Response) => {
  const page = req.query.page ? req.query.page : 1;
  const size = req.query.size ? req.query.size : 15;
  const filters = req.query.filters ? req.query.filters : {};
  const data = await dictServer.list(Number(page), Number(size), filters);
  res.json({
    data,
  });
};

// 字典下的分类
const category = async (req: Request, res: Response) => {
  const id = req.params.id;
  if (!id) {
    return res.json(Constant.LACK);
  }
  const data = await dictServer.category(id);
  return res.json({
    data,
  });
};

export default {
  paths,
  add,
  update,
  _delete,
  list,
  category,
};